import java.io.*;
import java.util.*;

/**
 * All game logic and processing, including generating solution and checking guesses.
 */
public class Game {
	static final int NPEGS = 4;
	static final int NGUESS = 4;
	static final int MAXGUESSES = 10;
	String _solution;
	int _guesses;
	String _pegs;
	boolean solved;
	final static String language = "RBGMOY";
	
	// generate a random solution
	/**
	 * Construct & generate random solution.
	 */
	Game() {
		Random rand = new Random();
		int x;
		StringBuilder builder = new StringBuilder(language.length());
		_guesses = 0;
		_pegs = "";
		_solution = "";
		for(x = 0; x < NGUESS; x++) {
			builder.append(language.charAt(rand.nextInt(language.length())));
		}
		solved = false;
		_solution = builder.toString();
		System.out.println("Solution: " + _solution);
	}
	/**
	 * Construct and pass in solution
	 * @param solution solution
	 */
	Game(String solution) {
		_solution = solution;
		_guesses = 0;
		_pegs = "";
		solved = false;
	}
	/**
	 * Returns true on correct guess
	 */
	boolean hasLost() {
		if(_guesses >= MAXGUESSES) {
			return true;
		}
		return false;
	}
	
	/**
	 * Returns black and white pegs
	 * @return feeback
	 */
	String getFeedback() {
		return _pegs;
	}
	
	/**
	 * Number of guesses so far
	 * @return number of guesses so far
	 */
	int getGuesses() {
		return _guesses;
	}
	
	/**
	 * Get solution
	 * @return solution
	 */
	String getSolution() {
		return _solution;
	}
	
	/**
	 * Game solved
	 * @return Return boolean true game is solved false game is not and the game is still running.
	 */
	boolean isSolved() {
		return solved;
	}
	/**
	 * Make a guess, This is checked against the solution and the feedback pegs are generated and the main counter
	 * is incremented. On success this sets solved to true.
	 * @param guess Guess attempt
	 */
	void guess(String guess) {
		int x;
		int nmarked = 0;
		String solution;
		solution = _solution;
		String pegs = new String();
		int marked[] = { 0, 0, 0, 0 }; // same amount as NPEGS
		Stack<Character> guessStack = new Stack<Character>();
		Stack<Character> solutionStack = new Stack<Character>();
		
		for(x = 0; x < NPEGS; x++) {
			if(guess.charAt(x) == solution.charAt(x)) {
				pegs = pegs.concat("B");
				marked[x] = 1;
			}
		}
		
		for(x = 0; x < NPEGS; x++) {
			
			if(marked[x] == 0) {
				guessStack.push(guess.charAt(x));
				solutionStack.push(solution.charAt(x));
			}
			else if(marked[x] == 1)
			{
				nmarked++;
			}
		}

		
		while(!guessStack.isEmpty()) {
			Character color;
			int index;
			color = guessStack.pop();
			index = solutionStack.indexOf(color);
			
			if(index != -1) {
				// match
				pegs = pegs.concat("W");
				solutionStack.remove(index);
			} else {
				// no match
				;
			}
		}
		_pegs = pegs;
		_guesses++;
		
		if(_solution.equals(guess)) {
			solved = true;
		}
	}
}
